<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
require_once __DIR__.'/../../../vendor/workerman/workerman/Autoloader.php';
class HbSub extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'hb';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->subscribe(function ($data){
            $this->info($data);
        });
    }

   public function subscribe($callback, $sub_str="market.btcusdt.kline.1min") {
        $GLOBALS['sub_str'] = $sub_str;
        $GLOBALS['callback'] = $callback;
        $worker = new Worker();
        $worker->onWorkerStart = function($worker) {
            // ssl需要访问443端口
            $con = new AsyncTcpConnection('ws://api.huobi.pro:443/ws');

            // 设置以ssl加密方式访问，使之成为wss
            $con->transport = 'ssl';

            $con->onConnect = function($con) {
                $data = json_encode([
                    'sub' => $GLOBALS['sub_str'],
                    'id' => 'depth' . time()
                ]);
                $con->send($data);
            };

            $con->onMessage = function($con, $data) {
                $data = gzdecode($data);
                $data = json_decode($data, true);
                if(isset($data['ping'])) {
                    $con->send(json_encode([
                        "pong" => $data['ping']
                    ]));
                }else{
                    call_user_func_array($GLOBALS['callback'], array($data));
                }
            };

            $con->connect();
        };

        Worker::runAll();
    }
}
